package com.tangkun.environment.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tangkun.environment.R;
import com.tangkun.environment.application.Session;
import com.tangkun.environment.entity.token.LoginReturn;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxActivityHelper;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.SharePrefercesUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 登陆页面
 */
public class LoginActivity extends BaseActivity {
    @BindView(R.id.bg)
    RelativeLayout bg;
    @BindView(R.id.et_login_telephone)
    EditText etLoginTelephone;
    @BindView(R.id.et_login_password)
    EditText etLoginPassword;
    @BindView(R.id.iv_login_show_or_hide)
    ImageView ivLoginShowOrHide;
    @BindView(R.id.iv_login_telephone_delete)
    ImageView ivLoginTelephoneDelete;
    @BindView(R.id.next)
    TextView next;
    @BindView(R.id.btn_login_login)
    Button btnLoginLogin;
    @BindView(R.id.tv_login_lianxikefu)
    TextView tvLoginLianxikefu;
    @BindView(R.id.tv_login_zhaohuimima)
    TextView tvLoginZhaohuimima;
    @BindView(R.id.divider)
    TextView divider;
    private Context mContext;

    /**
     * 是否显示密码
     */
    private boolean isShowPassword = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initListener();
        bg.setBackgroundColor(getResources().getColor(R.color.transparent));
        next.setText("注册");
        next.setTextColor(getResources().getColor(R.color.common_green));
        next.setVisibility(View.VISIBLE);
        divider.setVisibility(View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        //历史登录用户名
        String userName = SharePrefercesUtils.getUserName(mContext);
        if (!TextUtils.isEmpty(userName)) {
            etLoginTelephone.setText(userName);
            etLoginTelephone.setSelection(userName.length());
        }
        //历史登录密码
        String password = SharePrefercesUtils.getPassword(mContext);
        if (!TextUtils.isEmpty(password)) {
            etLoginPassword.setText(password);
            etLoginPassword.setSelection(password.length());
        }
    }

    private void initListener() {
        //输入框文字变化监听 显示与隐藏删除按钮
        etLoginTelephone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                // 搜索框中文字长度
                if (etLoginTelephone.getText().toString().length() > 0) {
                    ivLoginTelephoneDelete.setVisibility(View.VISIBLE);
                } else {
                    ivLoginTelephoneDelete.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    /**
     * 登录
     */
    private void login() {
        //手机号
        if (TextUtils.isEmpty(etLoginTelephone.getText().toString())) {
            showToast("请输入手机号");
            return;
        }
//        //是否是正确的手机号判断
//        if (!Utils.isTruePhone(etLoginTelephone.getText().toString())) {
//            showToast("请输入正确的手机号");
//            return;
//        }
        //密码
        if (TextUtils.isEmpty(etLoginPassword.getText().toString())) {
            showToast("请输入密码");
            return;
        }
        //调用登录接口，成功后跳转主页面MainActivity
        String username = etLoginTelephone.getText().toString();//手机号
        String password = etLoginPassword.getText().toString();//密码
        fromNetwork.login(username, password).compose(new RxActivityHelper<LoginReturn>().ioMain(LoginActivity.this, true))
                .subscribe(new MySubscribe<LoginReturn>(mContext, true) {

                    @Override
                    protected void success(LoginReturn resultBean) {
                        if (resultBean.data != null) {
                            //本地文件存储用户已登录
                            SharePrefercesUtils.setLoginStatus(mContext, true);
                            LogUtils.e("authmark:" + resultBean.data.authmark);
                            //刷新本地token
                            SharePrefercesUtils.setToken(mContext, resultBean.data.authmark);
                            //保存用户名
                            SharePrefercesUtils.setUserName(mContext, etLoginTelephone.getText().toString());
                            //保存密码
                            SharePrefercesUtils.setPassword(mContext, etLoginPassword.getText().toString());
                            //更新用户信息
                            Session.getInstance().setUserInfo(resultBean.data);
                            //是否绑定
                            if (resultBean.data.bindlist == null || resultBean.data.bindlist.size() == 0) {
                                SharePrefercesUtils.setBindStatus(mContext, false);
                            } else {
                                SharePrefercesUtils.setBindStatus(mContext, true);
                            }
                            //跳转主页
                            JumpHelper.jump(LoginActivity.this, MainActivity.class);
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }

    @OnClick({R.id.back, R.id.next, R.id.iv_login_telephone_delete, R.id.iv_login_show_or_hide, R.id.btn_login_login, R.id.tv_login_lianxikefu, R.id.tv_login_zhaohuimima})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back://返回
                JumpHelper.finish(mContext);
                break;
            case R.id.next://注册
                JumpHelper.jump(LoginActivity.this, RegistActivity.class, true);
                break;
            case R.id.iv_login_telephone_delete://清空
                etLoginTelephone.setText("");
                break;
            case R.id.iv_login_show_or_hide://显示和隐藏密码
                showOrHidePassword();
                break;
            case R.id.btn_login_login://登录
                login();
                break;
            case R.id.tv_login_lianxikefu://联系客服
                call();
                break;
            case R.id.tv_login_zhaohuimima://找回密码
                JumpHelper.jump(LoginActivity.this, ForgetPasswordActivity.class, false);
                break;
        }
    }

    /**
     * 显示与隐藏密码
     */
    private void showOrHidePassword() {
        if (isShowPassword) {//当前状态是显示密码，置为隐藏密码
            isShowPassword = false;
            ivLoginShowOrHide.setImageResource(R.mipmap.ic_mima_hide);
            //隐藏密码
            etLoginPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } else {//当前状态是隐藏密码，置为显示密码
            isShowPassword = true;
            ivLoginShowOrHide.setImageResource(R.mipmap.ic_mima_show);
            //显示密码
            etLoginPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        }
    }

    /**
     * 打电话
     */
    private void call() {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + "028-61383738");
        intent.setData(data);
        startActivity(intent);
    }

}
